package com.xsomnus.network_programming.netty.heartbeat;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 叶小夏
 * @since 2019-08-16 17:44
 */
public class ServerBizHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有链接了");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("链接失效了");
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf = (ByteBuf) msg;

        int readableBytes = byteBuf.readableBytes();

        byte[] target = new byte[readableBytes];

        byteBuf.readBytes(target);

        String str = new String(target, StandardCharsets.UTF_8);

        System.out.println(str);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常");
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println(evt);
       if (evt instanceof IdleStateEvent) {
           IdleStateEvent idleStateEvent  = (IdleStateEvent) evt;
           String s = idleStateEvent.toString();

           IdleState state = idleStateEvent.state();
           switch (state) {
               case READER_IDLE:
                   System.out.println(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + " READ IDLE " + s);
               case WRITER_IDLE:
                   System.out.println(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + " WRITE IDLE " + s);
               case ALL_IDLE:
                   System.out.println(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + " BOTH IDLE " + s);
           }
       }
    }
}
